//app.js
const baseUrl = require('./config').baseUrl
App({
  onLaunch(option) {
    this.userLogin()
    this.getcurrentPageUrl(option)
    // if (!wx.getStorageSync('userInfo')) {
    //   wx.reLaunch({
    //     url: '/pages/authorize/index'
    //   })
    // } else {
    //   this.globalData.userInfo = wx.getStorageSync('userInfo')
    // }
    debugger
    wx.reLaunch({
      url: '/pages/authorize/index'
    })
  },
  globalData: {
    // baseUrl: 'http://0.0.0.0:8090/#/epidemicFKEntery',
    traceUrl: 'https://zhaq-sit-manager.bosafe.com/app/#/addTrack',
    // traceUrl: 'https://zhaq-sit-manager.bosafe.com/apptest/#/addTrack',
    // traceUrl: 'http://localhost:8090/app/#/addTrack',
    baseUrl: 'https://zhaq-sit-manager.bosafe.com/app/#/epidemicFKEntery',
    // baseUrl: 'https://zhaq-sit-manager.bosafe.com/apptest/#/epidemicFKEntery',
    registerInfo: '',
    userInfo: ''
  },
  getcurrentPageUrl(option) {
    let queryStr = ''
    let queryKeys = Object.keys(option.query)
    queryKeys.forEach((key, index) => {
      if (index === 0) {
        queryStr += `?${key}=${option.query[key]}`
      } else {
        queryStr += `&${key}=${option.query[key]}`
      }
    })
    this.globalData.currentPageUrl = `/${option.path}${queryStr}`
  },
  onGotUserInfo() {
    // 获取用户信息
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId       
        this.globalData.userInfo = res.userInfo
        // wx.setStorageSync('userInfo', res.userInfo)
        wx.reLaunch({
          url: this.globalData.currentPageUrl
        })
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
  },
  userLogin() {
    let This = this
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: `${baseUrl}/api/Register/Get?code=${res.code}`,
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: 'GET',
            success: (res) => {
              if (res.data.code === 0) {
                This.globalData.registerInfo = res.data.data
                if (This.accountCallback) {
                  This.accountCallback();
                }
              } else {
                wx.showToast({
                  title: res.data.info,
                  icon: 'none',
                  duration: 1000
                })
              }
            },
            fail: (error) => {
              wx.showToast({
                title: error.data.info,
                icon: 'none',
                duration: 1000
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  }
})
